<?php namespace App\Http\Controllers\Api;

use App\Audios;
use App\Excels;
use App\Files;
use App\Http\Controllers\Controller;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Images;
use App\User;
use App\Userinfo;
use App\Videos;
use EasyWeChat\OfficialAccount\Server\Guard;
use Faker\Provider\Image;
use Illuminate\Http\Request;
use Log;

class ImageController extends Controller
{
    public function upload(Request $request){
        $uploadFile = $request->file('photo');

        if(!$request->hasFile('photo'))
            return response()->json(['level'=>'error','message'=>'图片不存在']);

        if(!$uploadFile->isValid())
            return response()->json(['level'=>'error','message'=>'图片上传失败']);

        $fileName = $uploadFile->getClientOriginalName();

        /** @var Files $fileModel */
        $fileModel = FileManager::UploadFile($uploadFile,$fileName,'oss');
//        $fileModel = FileManager::UploadFile($uploadFile,$fileName,'oss');

        if($fileModel){
            $imageModel = Images::whereFileId($fileModel->id)->first();
            if(!$imageModel){
                $imageModel = new Images();
                $imageModel->file_id = $fileModel->id;
                $imageModel->img_name= $fileName;
                $imageModel->img_type= $fileModel->file_type;
                $imageModel->save();
            }
        }else{
            $imageModel = null;
        }

//        if($fileModel->file_type == '.svg'){
//            $imageModel = Images::whereFileId($fileModel->id)->first();
//            if(!$imageModel){
//                $imageModel = new Images();
//                $imageModel->file_id = $fileModel->id;
//                $imageModel->img_name= $fileName;
//                $imageModel->img_type= $fileModel->file_type;
//                $imageModel->save();
//            }
//        }else{
//            $imageModel = FileManager::buildImageMultipx($fileModel);
//        }


        if(!is_null($imageModel)){
            $imageModel->img_url = FileManager::getImgUrl($imageModel->id);
            return response()->json(['level'=>'success','message'=>'图片上传成功','data'=>$imageModel]);
        }

        $imageModel->img_url = FileManager::getImgUrl(0);

        return response()->json(['level'=>'success','message'=>'图片上传成功','data'=>$imageModel]);
    }

    public function uploadExcel(Request $request){
        $uploadFile = $request->file('excel');

        if(!$request->hasFile('excel'))
            return response()->json(['level'=>'error','message'=>'图片不存在']);

        if(!$uploadFile->isValid())
            return response()->json(['level'=>'error','message'=>'图片上传失败']);

        $fileName = $uploadFile->getClientOriginalName();

        /** @var Files $fileModel */
        $fileModel = FileManager::UploadFile($uploadFile, $fileName);

        $theExcel = new Excels();
        $theExcel->file_id = $fileModel->id;
        $theExcel->key     = $fileModel->file_md5;
        $theExcel->excel_name = $fileModel->file_name;
        $theExcel->excel_type = $fileModel->file_type;
        $theExcel->save();

        $theExcel->excel_url = route("Api.File.showExcelById",["id"=>$theExcel->id]);;

        return response()->json(['level'=>'success','message'=>'上传成功！','data'=>$theExcel]);
    }

    public function showExcelById($id=0){
        /** @var Excels $thatExcel */
        $thatExcel = Excels::whereId($id)->first();
        if(!$thatExcel)
            return false;

        /** @var Files $file */
        $file= Files::whereId($thatExcel->file_id)->first();
        if(!$file)
            return false;

        return \Response::download($file->getLocalPath(),$thatExcel->excel_name,[],'inline');
    }

    /**
     * 营业执照图片上传
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function businessLicenseUpload(Request $request){
        $uploadFile = $request->file('photo');

        if(!$request->hasFile('photo'))
            return response()->json(['level'=>'error','message'=>'图片不存在']);

        if(!$uploadFile->isValid())
            return response()->json(['level'=>'error','message'=>'图片上传失败']);

        $fileName = $uploadFile->getClientOriginalName();

        $fileModel = FileManager::UploadFile($uploadFile,$fileName);
        if($fileModel){
            $imageModel = Images::whereFileId($fileModel->id)->first();
            if(!$imageModel){
                $imageModel = new Images();
                $imageModel->file_id = $fileModel->id;
                $imageModel->img_name= $fileName;
                $imageModel->img_type= $fileModel->file_type;
                $imageModel->save();
            }
        }else{
            $imageModel = null;
        }

        if(!is_null($imageModel)){
            $imageModel->img_url = FileManager::getImgUrl($imageModel->id);

            return response()->json(['level'=>'success','message'=>'图片上传成功','data'=>$imageModel]);
        }

        $imageModel->img_url = FileManager::getImgUrl(0);

        return response()->json(['level'=>'success','message'=>'图片上传成功','data'=>$imageModel]);
    }

    public function uploadAudio(Request $request){
        $uploadFile = $request->file('audio');

        if (!$request->hasFile('audio'))
            return response()->json(['level'=>'error','message'=>'文件不存在！']);

        if (!$uploadFile->isValid())
            return response()->json(['level'=>'error','message'=>'上传失败！']);

        $fileName = $uploadFile->getClientOriginalName();

        /** @var Files $fileModel */
        $fileModel = FileManager::UploadFile($uploadFile, $fileName,"oss");

        $theVAudio = new Audios();
        $theVAudio->file_id = $fileModel->id;
        $theVAudio->key     = $fileModel->file_md5;
        $theVAudio->audio_name = $fileModel->file_name;
        $theVAudio->audio_type = $fileModel->file_type;
        $theVAudio->save();

        $theVAudio->audio_url = FileManager::getAudioUrl($theVAudio->id);

        return response()->json(['level'=>'success','message'=>'上传成功！','data'=>$theVAudio]);
    }

    public function uploadVideo(Request $request){
        $uploadFile = $request->file('video');

        if (!$request->hasFile('video'))
            return response()->json(['level'=>'error','message'=>'文件不存在！']);

        if (!$uploadFile->isValid())
            return response()->json(['level'=>'error','message'=>'上传失败！']);

        $fileName = $uploadFile->getClientOriginalName();

        /** @var Files $fileModel */
        $fileModel = FileManager::UploadFile($uploadFile, $fileName);

        $theVideo = new Videos();
        $theVideo->file_id = $fileModel->id;
        $theVideo->key     = $fileModel->file_md5;
        $theVideo->video_name = $fileModel->file_name;
        $theVideo->video_type = $fileModel->file_type;
        $theVideo->save();

        $theVideo->video_url = FileManager::getVideoUrl($theVideo->id);

        return response()->json(['level'=>'success','message'=>'上传成功！','data'=>$theVideo]);
    }

    public function showImageById(Request $request){
//        Log::error('img_id=' . $id);
        $id = $request->id;
        if(is_numeric($id) && $id == 0)
            return \Response::download('images/default_img.png','default_img.png',[],'inline');

        /** @var Images $images */
        $images = Images::whereId($id)->first();

        if(!$images)
            return \Response::download('images/default_img.png','default_img.png',[],'inline');

        $imageFile = $images->files;
        if(!$imageFile || $imageFile == null)
            return \Response::download('images/default_img.png','default_img.png',[],'inline');

        return \Response::download($imageFile->getLocalPath(),$imageFile->img_name,[],'inline');
    }


    public function uploadUserPhoto(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(["level"=>"error","message"=>"no_login","data"=>"no_login"]);

        /** @var Userinfo $userInfo */
        $userInfo = Userinfo::whereUserId($user->id)->first();

        if(!$userInfo)
            return response()->json(["level"=>"error","message"=>"用户信息不存在","data"=>""]);

        $uploadFile = $request->file('photo');

        if(!$request->hasFile('photo'))
            return response()->json(['level'=>'error','message'=>'图片不存在']);

        if(!$uploadFile->isValid())
            return response()->json(['level'=>'error','message'=>'图片上传失败']);

        $fileName = $uploadFile->getClientOriginalName();

        /** @var Files $fileModel */
        $fileModel = FileManager::UploadFile($uploadFile,$fileName,'local');
        /** @var Images $imageModel */
        $imageModel = FileManager::buildImageMultipx($fileModel);

        $userInfo->photo_id = $imageModel->id;
        $userInfo->save();

        return response()->json(['level'=>'success','message'=>'头像上传成功','data'=>(int)$imageModel->id]);
    }

    /**
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function uploadBase64Image(Request $request){
        $allBase64 = $request->get('base_code');

        $imgBase64 = explode('base64,',$allBase64);

        $imgContent = base64_decode($imgBase64[1]);

        $fileMd5 = md5($imgContent);

        /** @var Files $fileModel */
        $fileModel = Files::whereFileMd5($fileMd5)->first();
        if(!$fileModel){
            $fileModel = FileManager::UploadBase64($imgContent);
        }

        /** @var Images $thatImage */
        $thatImage = Images::whereFileId($fileModel->id)->first();
        if(!$thatImage){
            $thatImage = new Images();
            $thatImage->file_id = $fileModel->id;
            $thatImage->img_name = $fileModel->file_name;
            $thatImage->img_type = $fileModel->file_type;
            $thatImage->save();
        }

        $thatImage->img_url = FileManager::getImgUrl($thatImage->id);

        return response()->json(["level"=>"success","message"=>"上传成功！","data"=>$thatImage]);
    }

    public function reloadImages(){
        $allFiles = Files::all();

        foreach ($allFiles as $allFile){
            if($allFile->disk == "local"){
                $allFile->disk = "oss";
                $allFile->file_url = "uploads/".$allFile->file_url;
                $allFile->save();
            }
        }

        echo "success";
    }

//    public function docQrcode(Guard $guard){
//        $qrCode = new QrCode();
//        $qrCode
//            ->setText(route('Api.User.followDocByQrcode').'?doc_id='.$user->id)
//            ->setSize(250)
//            ->setPadding(10)
//            ->setErrorCorrection('high')
//            ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
//            ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
//            ->setImageType(QrCode::IMAGE_TYPE_PNG)
//        ;
//
//        // now we can directly output the qrcode
//        header('Content-Type: '.$qrCode->getContentType());
//        $qrCode->render();
//
//        // or create a response object
//        $response = new Response($qrCode->get(), 200, ['Content-Type' => $qrCode->getContentType()]);
//
//        return $response;
//    }
}
